package com.time.gateway.filter;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.google.gson.Gson;
import com.time.gateway.constants.GatewayConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 登录过滤器类
 *
 * @author: HuangQi
 * @date: Created in 16:41 2025/8/29
 * @description: 登录过滤器
 */
@Component
@Slf4j
public class LoginFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String url = request.getURI().getPath();
        log.info("LoginFilter.filter.url:{}", url);

        // 路径匹配优化
        if (GatewayConstant.LOGIN_PATH.equals(url)) {
            return chain.filter(exchange);
        }

        // 获取 token 信息并处理为空的情况
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        if (tokenInfo == null) {
            log.warn("LoginFilter.filter.tokenInfo: Token information is null");
            return chain.filter(exchange);
        }

        // 添加 loginId 到请求头
        String loginId = (String) tokenInfo.getLoginId();
        ServerHttpRequest mutatedRequest = request.mutate()
                .header(GatewayConstant.LOGIN_HEADER, loginId)
                .build();

        // 继续过滤链
        return chain.filter(exchange.mutate().request(mutatedRequest).build());
    }
}
